package cn.controller;

import cn.common.ExceResult;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.common.PageString;
import cn.filter.LoginCheck;
import cn.kpi.entity.lawassessment.*;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.teamassessment.BUAssTemplateOrgEntity;
import cn.kpi.entity.usualassessment.OrgTitle;
import cn.kpi.service.lawassessment.ILawAssTemplateService;
import cn.kpi.service.lawassessment.ILawKPIService;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.teamassement.IBUAssTemplateService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.*;

@Controller
@RequestMapping("lawass")
public class LawAssessController extends BaseController {

    @Autowired
    private ILawAssTemplateService iLawAssTemplateService;

    @Autowired
    private IBUAssTemplateService ibuAssTemplateService;

    @Autowired
    private ILawKPIService iLawKPIService;


    @Autowired
    private IOrgService orgService;

    //region 指标部分
    @RequestMapping(value = "/index_list")
    public String IndexList(Model model) {
        return "lawassessment/law_index_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_index_list")
    public GridCommon<LawAssTempCreateIndexEntity> GetIndexList(HttpServletRequest request) {
        List<LawAssTempCreateIndexEntity> lst = null;
        GridCommon<LawAssTempCreateIndexEntity> countlist = new GridCommon<LawAssTempCreateIndexEntity>();
        try {

            String where = "";
            lst = iLawAssTemplateService.GetIndexListByWhere(where);

            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");

        } catch (Exception e) {
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }


    @RequestMapping(value = "/index_edit")
    public String IndexEdit(Model model, Long assindexid) {
        try {
            String where = " AND assindextype=0";
            List<LawAssTemplateIndexEntity> lst = iLawAssTemplateService.GetTemplateIndexListByWhere(where);
            model.addAttribute("lst", lst);
            LawAssTemplateIndexEntity entity = new LawAssTemplateIndexEntity();
            if (assindexid > 0) {
                entity = iLawAssTemplateService.GetIndexById(assindexid);
            }
            model.addAttribute("entity", entity);

        } catch (Exception ex) {

        }
        return "lawassessment/law_index_edit";
    }

    @RequestMapping(value = "/add_templateindex")
    public String AddTemplateindex(HttpServletRequest request, HttpServletResponse response) {
        try {
            LawAssTemplateIndexEntity entity = new LawAssTemplateIndexEntity();
            if (request.getParameter("assindexid") == null || request.getParameter("assindexid").equals("")) {
                entity.setAssindexid(0L);
            } else {
                entity.setAssindexid(Long.parseLong(request.getParameter("assindexid")));
            }

            entity.setAssindextype(Integer.parseInt(request.getParameter("assindextype")));
            entity.setByuserid(this.GetLoginUserId());
            entity.setParentid(Long.valueOf(request.getParameter("parentid")));
//            entity.setScore(Integer.parseInt(request.getParameter("score")));
            entity.setTemplateid(Long.valueOf(0));
            if (entity.getAssindextype() == 1) {
                entity.setUassingredients(request.getParameter("uasscontent").trim());
                entity.setEvaluationstandard(request.getParameter("evaluationstandard").trim());
            } else {
                entity.setUasscontent(request.getParameter("uasscontent").trim());
            }

            int iResult = 0;
            if (entity.getAssindexid() > 0) {
                iResult = iLawAssTemplateService.UpdateIndex(entity);
            } else {
                if (entity.getParentid() == 0) {
                    entity.setScore(0);
                }
                iResult = iLawAssTemplateService.InsertTemplateIndexentity(entity);
            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete_index")
    public ExceResult DeleteIndex(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long assindexid = Long.parseLong(request.getParameter("assindexid"));
            Long parentid = Long.parseLong(request.getParameter("parentid"));
            int iResult = iLawAssTemplateService.DeleteIndex(assindexid, parentid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }
    //endregion

    //region 模板编辑
    @RequestMapping(value = "/law_template_list_alone_edit")
    public String TemplateListAloneEdit(Model model, Long templateid) {
        try {
            List<LawAssTemplateIndexEntity> lst = iLawAssTemplateService.GetTemplateIndexListRowSpanByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);

            String parentid = "";
            String usassid = "";
            for (int i = 0; i < lst.size(); i++) {
                LawAssTemplateIndexEntity entity = lst.get(i);
                usassid += entity.getAssindexid().toString() + ",";
                if (parentid.length() > 0) {
                    String[] strarr = parentid.split(",");
                    String last = strarr[strarr.length - 1];
                    if (!last.equals(entity.getParentid().toString())) {
                        parentid += entity.getParentid().toString() + ",";
                    }
                } else {
                    parentid += entity.getParentid().toString() + ",";
                }

            }
            PageString pagestring = new PageString();
            pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
            pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
            model.addAttribute("pagestring", pagestring);

            if (templateid > 0) {
                LawAssTemplateEntity ustempentity = iLawAssTemplateService.GetLawAssTemplateListById(templateid);
                model.addAttribute("ustempentity", ustempentity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "lawassessment/law_template_list_alone_edit";
    }

    @RequestMapping(value = "/create_templateindex")
    public String CreateTemplateIndex(HttpServletRequest request, HttpServletResponse response) {
        try {
            String strtemplateid = request.getParameter("templateid");
            Long templateid = Long.parseLong(strtemplateid);


            String parentids = request.getParameter("parentids");
            String assindexids = request.getParameter("assindexids");

            String[] parentidsArr = parentids.split(",");
            String[] assindexidsArr = assindexids.split(",");

            Long flag = 0L;
            List<LawAssTempCreateIndexEntity> lst = new ArrayList<LawAssTempCreateIndexEntity>();

            Long byuserid = this.GetLoginUserId();
            for (int i = 0; i < assindexidsArr.length; i++) {
                if (request.getParameter("cb_" + assindexidsArr[i]) != null) {
                    LawAssTempCreateIndexEntity entity = new LawAssTempCreateIndexEntity();
                    entity.setAssindexid(Long.parseLong(assindexidsArr[i]));
                    entity.setAssindextype(1);
                    entity.setParentid(Long.parseLong(request.getParameter("parentid_" + assindexidsArr[i])));
                    entity.setTemplateid(templateid);
                    entity.setEvaluationstandard(request.getParameter("evaluationstandard_" + assindexidsArr[i]));
//                    entity.setScore(Integer.parseInt(request.getParameter("score_" + assindexidsArr[i])));
                    entity.setUassingredients(request.getParameter("uassingredients_" + assindexidsArr[i]));
                    entity.setUasscontent(request.getParameter("uasscontent_" + entity.getParentid()));
                    entity.setByuserid(byuserid);
                    lst.add(entity);
                }
            }

            if (lst.size() <= 0) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'请选择指标项')</script>");
            }
            LawAssTemplateEntity tempentity = new LawAssTemplateEntity();

            tempentity.setTemplatename(request.getParameter("templatename"));
            tempentity.setBegintime(Date.valueOf(request.getParameter("begintime") + "-01"));
//            tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
            tempentity.setTemplatedes(request.getParameter("templatedes"));
            tempentity.setByuserid(byuserid);
            int iResult = 0;
            if (templateid > 0) {
                tempentity.setTemplateid(templateid);
                iResult = iLawAssTemplateService.UpdateLawAssTempEntity(lst, tempentity);
            } else {
                iResult = iLawAssTemplateService.CreateTemplateAndIndex(lst, tempentity);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @RequestMapping(value = "/law_template_list_alone")
    public String TemplateListAlone(Model model) {
        return "lawassessment/law_template_list_alone";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<LawAssTemplateEntity> GetList(HttpServletRequest request) {

        List<LawAssTemplateEntity> lst = null;
        LayTable<LawAssTemplateEntity> layTable = new LayTable<LawAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND templatename LIKE '%" + templatename.trim() + "%'";
            }

            lst = iLawAssTemplateService.GetLawAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iLawAssTemplateService.GetLawAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_template")
    public ExceResult DeleteTemplate(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            int iResult = iLawAssTemplateService.DeleteLawTempEntity(templateid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @RequestMapping(value = "/law_templae_list_org_edit")
    public String templateOrgEdit(Model model, Long templateid) {
        try {
            List<LawAssTemplateOrgEntity> lst = iLawAssTemplateService.GetTempOrgListByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "lawassessment/law_templae_list_org_edit";
    }

    @ResponseBody
    @RequestMapping(value = "/create_templateorg")
    public ExceResult CreateTemplateOrg(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String orgid = request.getParameter("origid");
            Long templateidl = Long.parseLong(request.getParameter("templateid"));

            String[] oridArr = orgid.split(",");

            Long byuserid = this.GetLoginUserId();//未使用

            List<Long> orgList = new ArrayList<>();
            for (String s : oridArr) {
                orgList.add(Long.valueOf(s));
            }
            int iResult = iLawAssTemplateService.InsertLawTempOrgBatch(templateidl, orgList);

            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //endregion

    //region 指标打分部分
    @RequestMapping(value = "/law_kp_list")
    public String kpiListView(Model model) {
        return "lawassessment/law_kp_list";
    }

    //模板
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_kpi_list")
    public LayTable<LawAssTemplateEntity> GetkpiList(HttpServletRequest request) {

        List<LawAssTemplateEntity> lst = null;
        LayTable<LawAssTemplateEntity> layTable = new LayTable<LawAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND templatename LIKE '%" + templatename.trim() + "%'";
            }

            lst = iLawAssTemplateService.GetLawAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iLawAssTemplateService.GetLawAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/law_kp_look")
    public String kpiLook(Model model) {
        try {
            Long templateid = Long.parseLong("15");
            List<LawAssTempCreateIndexEntity> lstdetail = iLawAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";
            String groupColums = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                groupColums += "'" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);
            groupColums = groupColums.substring(0, groupColums.length() - 1);
            List<Map> lstorg = iLawKPIService.GetLawKPIMapByTempIdAndColumns(templateid, columns, groupColums);
            List<Map> list = iLawKPIService.getRedScore(templateid);
            for (int i = 0; i < lstorg.size(); i++) {

                for (int j = 0; j < list.size(); j++) {

                    if (lstorg.get(i).get("orgid").toString().equals(list.get(j).get("orgid").toString())) {

                        lstorg.get(i).put("redscore", list.get(j).get("redscore"));
                        lstorg.get(i).put("sumscore", list.get(j).get("sumscore"));
                        break;

                    }


                }

            }
            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {

        }
        return "lawassessment/law_kp_look";

    }


    @RequestMapping(value = "/look")
    public String kpiLooks(Model model, Long templateid) {
        try {

            List<LawAssTempCreateIndexEntity> lstdetail = iLawAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";
            String groupColums = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "SUM(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                groupColums += "'" + lstdetail.get(i).getAssindexid() + "',";
                String where = "templateid=" + templateid + " AND  assindexid=" + lstdetail.get(i).getAssindexid();
                List<Map> weights = iLawAssTemplateService.getWeight(where);
                for (int j = 0; j < weights.size(); j++) {

                    if (j == 0) {
//                        model.addAttribute(lstdetail.get(i).getAssindexid() + "", weights.get(j).get("kpiweight"));
                        lstdetail.get(i).setKpiweight(new BigDecimal(weights.get(j).get("kpiweight").toString()));


                    }

                }
            }
            columns = columns.substring(0, columns.length() - 1);
            groupColums = groupColums.substring(0, groupColums.length() - 1);

            List<Map> lstorg = iLawKPIService.GetLawKPIMapByTempIdAndColumns(templateid, columns, groupColums);

            List<Map> list = iLawKPIService.getRedScore(templateid);
            for (int i = 0; i < lstorg.size(); i++) {

                for (int j = 0; j < list.size(); j++) {

                    if (lstorg.get(i).get("orgid").toString().equals(list.get(j).get("orgid").toString())) {

                        lstorg.get(i).put("redscore", list.get(j).get("redscore"));
                        lstorg.get(i).put("sumscore", list.get(j).get("sumscore"));
                        break;

                    }


                }

            }


            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {
            String mess = e.getMessage();

        }
        return "lawassessment/look";

    }


    @RequestMapping(value = "/law_kp_read")
    public String kpiread(Model model, Long templateid) {
        try {
            List<LawAssTempCreateIndexEntity> lstdetail = iLawAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";
            String groupColums = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                groupColums += "'" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);
            groupColums = groupColums.substring(0, groupColums.length() - 1);

            List<Map> lstorg = iLawKPIService.GetLawKPIMapByTempIdAndColumns(templateid, columns, groupColums);

            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {

        }
        return "lawassessment/law_kp_read";
    }

    @ResponseBody
    @RequestMapping(value = "/getWeight")
    public List<Map> getWeight(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("templateid"));


        List<Map> map = iLawKPIService.GetWeight(id);
        return map;

    }

    @ResponseBody
    @RequestMapping(value = "/saveName")
    public String saveName(HttpServletRequest request, HttpServletResponse response) {

        String name = request.getParameter("name");
        Long templateid = Long.parseLong(request.getParameter("templateid"));
        LawAssTemplateEntity lawAssTemplateEntity = new LawAssTemplateEntity();
        lawAssTemplateEntity.setTemplateid(templateid);
        lawAssTemplateEntity.setDataname(name);
        iLawAssTemplateService.UpdateTName(lawAssTemplateEntity);

        return "";
    }


    @RequestMapping(value = "/law_kp_edit")
    public String kpiedit(Model model, Long templateid) throws IOException {
        try {
            List<LawAssTempCreateIndexEntity> lstdetail = iLawAssTemplateService.GetTemplateIndexBytemplateid(templateid);

            String columns = "";
            String groupColums = "";
            for (int i = 0; i < lstdetail.size(); i++) {

                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                groupColums += "'" + lstdetail.get(i).getAssindexid() + "',";
                String where = "templateid=" + templateid + " AND  assindexid=" + lstdetail.get(i).getAssindexid();
                List<Map> weights = iLawAssTemplateService.getWeight(where);
                if (weights != null) {
                    if (weights.size() <= 0) {
                        lstdetail.get(i).setKpiweight(new BigDecimal(100));


                    }
                }


                for (int j = 0; j < weights.size(); j++) {

                    if (j == 0) {
//                        model.addAttribute(lstdetail.get(i).getAssindexid() + "a", weights.get(j).get("kpiweight"));

                        if (weights.get(j).get("kpiweight") != null)
                        lstdetail.get(i).setKpiweight(new BigDecimal(weights.get(j).get("kpiweight").toString()));
                    }

                }

            }


            columns = columns.substring(0, columns.length() - 1);
            groupColums = groupColums.substring(0, groupColums.length() - 1);
            //实际数据
            List<Map> lstorg = iLawKPIService.GetLawKPIMapByTempIdAndColumns(templateid, columns, groupColums);
            List<Map> list1 = iLawKPIService.getRedScore(templateid);
            for (int i = 0; i < lstorg.size(); i++) {

                for (int j = 0; j < list1.size(); j++) {

                    if (lstorg.get(i).get("orgid").toString().equals(list1.get(j).get("orgid").toString())) {

                        lstorg.get(i).put("redscore", list1.get(j).get("redscore"));
                        lstorg.get(i).put("sumscore", list1.get(j).get("sumscore"));
                        break;

                    }


                }

            }
            //应该有的岗位数据
            List<LawAssTemplateOrgEntity> buAssTemplateOrgEntities = iLawAssTemplateService.GetChooseOrgListByTempId(templateid);
            List<Map> newMaps = new ArrayList<>();
            //数据合并
            for (LawAssTemplateOrgEntity buAssTemplateOrgEntity : buAssTemplateOrgEntities) {
                boolean isContent = false;
                long orgid = buAssTemplateOrgEntity.getOrgid();
                for (Map map : lstorg) {//是否已经有值
                    if (map.get("orgid") == orgid) {
                        isContent = true;
                        newMaps.add(map);
                    }
                }
                if (!isContent) {//初始化数据
                    Map mape = new HashMap();
                    mape.put("orgid", orgid);
                    mape.put("orgname", buAssTemplateOrgEntity.getOrgname());
                    mape.put("templateid", templateid);

                    for (LawAssTempCreateIndexEntity indexEntity : lstdetail) {
                        mape.put(indexEntity.getAssindexidcolum(), "100");
                    }
                    newMaps.add(mape);
                }
            }
            lstorg.addAll(newMaps);
            List<Map> list = new ArrayList<>();
            System.out.println(JSON.toJSONString(lstorg));
            for (int i = 0; i < newMaps.size(); i++) {
                list.add(newMaps.get(i));
            }
            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", list);
            model.addAttribute("templateid", templateid);
        } catch (Exception e) {
            txtExport.creatTxtFile("执法考核");
            StackTraceElement[] stackTrace = e.getStackTrace();
            String errorMsg = e.toString() + "<br/>";
            for (int i = 0; i < stackTrace.length; i++) {
                errorMsg += stackTrace[i];
                errorMsg += "<br/>";
            }
            txtExport.writeTxtFile(errorMsg);
        }
        return "lawassessment/law_kp_edit";
    }
    @RequestMapping(value = "/law_kp_edit_export")
    public String law_kp_edit_export(Model model, Long templateid) {
        try {
            List<LawAssTempCreateIndexEntity> lstdetail = iLawAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";
            String groupColums = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                groupColums += "'" + lstdetail.get(i).getAssindexid() + "',";
                String where = "templateid=" + templateid + " AND  assindexid=" + lstdetail.get(i).getAssindexid();
                List<Map> weights = iLawAssTemplateService.getWeight(where);
                for (int j = 0; j < weights.size(); j++) {
                    if (j == 0) {
//                        model.addAttribute(lstdetail.get(i).getAssindexid() + "", weights.get(j).get("kpiweight"));
                        lstdetail.get(i).setKpiweight(new BigDecimal(weights.get(j).get("kpiweight").toString()));
                    }
                }
            }
            columns = columns.substring(0, columns.length() - 1);
            groupColums = groupColums.substring(0, groupColums.length() - 1);
            List<Map> lstorg = iLawKPIService.GetLawKPIMapByTempIdAndColumns(templateid, columns, groupColums);
            List<Map> list = iLawKPIService.getRedScore(templateid);
            for (int i = 0; i < lstorg.size(); i++) {

                for (int j = 0; j < list.size(); j++) {

                    if (lstorg.get(i).get("orgid").toString().equals(list.get(j).get("orgid").toString())) {

                        lstorg.get(i).put("redscore", list.get(j).get("redscore"));
                        lstorg.get(i).put("sumscore", list.get(j).get("sumscore"));
                        break;

                    }


                }

            }
            HashMap<String, String> hs = new HashMap<>();
            for (int i = 0; i < lstorg.size(); i++) {
                if (!hs.containsKey(lstorg.get(i).get("sumscore"))) {
                    hs.put(lstorg.get(i).get("sumscore").toString(), "");
                }
            }
            float[] descArray = new float[hs.size()];
            int index = 0;
            for (String key : hs.keySet()) {
                descArray[index] = Float.parseFloat(key);
                index++;
            }
            Arrays.sort(descArray);
            int orderIndex = 0;
            for (int i = descArray.length - 1; i >= 0; i--) {
                orderIndex++;
                for (int j = 0; j < lstorg.size(); j++) {
                    if (descArray[i] == Float.parseFloat(lstorg.get(j).get("sumscore").toString())) {
                        lstorg.get(j).put("orderindex", orderIndex);
                    }
                }
            }
            List<Map> listTitle = ibuAssTemplateService.getTitle(templateid, "l","1,2,m");
            String title = "";
            if (list.size() > 0) {
                title = listTitle.get(0).get("title").toString();
            }
            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);
             model.addAttribute("title",title);

        } catch (Exception ex) {
        }
        return "lawassessment/law_kp_edit_export";
    }
    @RequestMapping(value = "/create_kpiscore")
    public String CreateKpiScore(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<LawKPItemEntity> bukpItemEntities = new ArrayList<>();
            //获取所有的值
            Map<String, String> map = new HashMap<>();
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String value = request.getParameter(name);
                map.put(name, value);
            }
            Long templateId = Long.valueOf(map.get("templateid"));
            for (String key : map.keySet()) {
                if (!key.equals("templateid") && !key.contains("w_") && !key.contains("red_")) {
                    String[] indexs = key.split("_");
                    LawKPItemEntity bukpItemEntity = new LawKPItemEntity();
                    bukpItemEntity.setTemplateid(templateId);
                    bukpItemEntity.setOrgid(Long.valueOf(indexs[1]));
                    bukpItemEntity.setAssindexid(Long.valueOf(indexs[2]));

                    if (map.get(key) != null && map.get(key).trim() != "") {
                        BigDecimal score = new BigDecimal(map.get(key)); //利率
                        bukpItemEntity.setScore(score);
                    } else {
                        bukpItemEntity.setScore(new BigDecimal("0"));
                    }
                    String weightKey = "w_" + bukpItemEntity.getAssindexid();
                    if (map.get(weightKey) != null && map.get(weightKey).trim() != "")
                        bukpItemEntity.setWeight(Float.parseFloat(map.get(weightKey)));
                    String redKey = "red_" + bukpItemEntity.getOrgid();
                    if (map.get(redKey) != null && map.get(redKey).trim() != "")
                        bukpItemEntity.setRedscore(Float.parseFloat(map.get(redKey)));
                    bukpItemEntities.add(bukpItemEntity);
                }
            }


            List<LawKPItemEntity> newbukpItemEntities = new ArrayList<>();
            for (int i = 0; i < bukpItemEntities.size(); i++) {
                LawKPItemEntity bukpItemEntity = bukpItemEntities.get(i);

                BigDecimal weight = BigDecimal.valueOf(bukpItemEntity.getWeight());
                BigDecimal score = bukpItemEntity.getScore().multiply(weight).divide(BigDecimal.valueOf(100));
                bukpItemEntity.setSumscore(score);
                newbukpItemEntities.add(bukpItemEntity);


            }

            int iResult = iLawKPIService.InsertLawKPItemBatch(templateId, newbukpItemEntities);
            if (iResult > 0) {

               // iLawAssTemplateService.updateSubmit(templateId, 1);

            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/submit")
    public ExceResult submit(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));

            int iResult = iLawAssTemplateService.updateSubmit(templateid, 2);
            result.setCode(200);
            result.setResult(iResult);
            result.setMsg("操作成功");
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //endregion
    @ResponseBody
    @RequestMapping(value = "/get_CheckorgList")
    public List<LawAssTemplateOrgEntity> getCheckOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<LawAssTemplateOrgEntity> lst = new ArrayList<>();
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            lst = iLawAssTemplateService.GetTempOrgListByTempId(templateid);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lst;
    }


    @ResponseBody
    @RequestMapping(value = "/get_orgList")
    public GridCommon<OrgEntity> getOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<OrgEntity> list = new ArrayList<>();
        GridCommon<OrgEntity> rs = new GridCommon<>();
        try {


            list = orgService.GetOrgListByWhere("  and  orgtype=0 ");
            rs.setCountRecord(list.size());
            rs.setItems(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return rs;
    }

    @ResponseBody
    @RequestMapping(value = "/add_title")
    public String addTitle(HttpServletRequest request, HttpServletResponse response) {


        try {

            String title = request.getParameter("title");
            Long templateId = Long.valueOf(request.getParameter("templateId"));

            OrgTitle orgTitle = new OrgTitle();
            String type = "l";
            orgTitle.setTitle(title);
            orgTitle.setType(type);
            orgTitle.setTemplateId(templateId);
            ibuAssTemplateService.addTitle(orgTitle,"m");

        } catch (Exception ex) {


        }
        return "";
    }

    @ResponseBody
    @RequestMapping(value = "/get_title")
    public List<Map> getTitle(HttpServletRequest request, HttpServletResponse response) {


        try {


            Long templateId = Long.valueOf(request.getParameter("templateId"));

            return ibuAssTemplateService.getTitle(templateId, "l","1,2,m");

        } catch (Exception ex) {


        }
        return null;
    }

}
